package com.hrd.admin.system.customer;

import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageInfo;
import com.hrd.admin.base.BaseDefine;
import com.hrd.common.util.bean.ServiceResult;
import com.hrd.mybatis.bean.auto.TMLArchives;
import com.hrd.mybatis.bean.ext.ExtCustomModel;
import com.hrd.mybatis.mapper.auto.TMLArchivesMapper;
import com.hrd.service.CustomerService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * @author 刘江宁
 * @create 2022/1/10 13:47
 * 客户信息
 */
@RestController
@RequestMapping("/system/customer")
@Slf4j
public class CustomerController {
    @Autowired
    TMLArchivesMapper tmlArchivesMapper;


    @Autowired
    CustomerService customerService;

    /**
     * 跳转统计页面
     *
     * @return
     */
    @RequestMapping("init")
    public ModelAndView init() {
        ModelAndView modelAndView = new ModelAndView("/system/customer/customer_list");
        return modelAndView;
    }

    /**
     * 手动同步客户信息
     *
     * @return
     */
    @RequestMapping("manual")
    public ServiceResult<String> manual() {
        return customerService.syncCustomerInfo();
    }

    @RequestMapping(value = "searchAction")
    public JSONObject searchAction(HttpServletRequest request, @ModelAttribute(BaseDefine.FORM) TMLArchives form) {
        // 创建分页
        return this.createPage(request, form);
    }

    /**
     * 创建分页机能
     *
     * @param request
     * @param form
     */
    private JSONObject createPage(HttpServletRequest request, TMLArchives form) {

        JSONObject object = new JSONObject();
        // 翻页
        form.setLimitStart(Integer.parseInt(form.getOffset()));
        form.setLimitEnd(Integer.parseInt(form.getOffset()) + Integer.parseInt(form.getLimit()));

        ServiceResult<List<ExtCustomModel>> result = customerService.list(form);
        Integer count = customerService.count(form);

        if (result != null) {
            List<ExtCustomModel> recordList = result.getResult();
            PageInfo paginator = new PageInfo(recordList);// 默认8页数据
            object.put("rows", paginator.getList());
            object.put("total", count);
        }

        return object;
    }
}
